#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
enum
{
    SOCKERROR = 2,
    BINDERROR,
    LISTENERROR,
};
const int backlog = 10;
class MySocket
{
public:
    MySocket()
    {
    }
    ~MySocket()
    {
    }

public:
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ == -1)
        {
            log(Fatal, "Socket fail,%s:%d", strerror(errno), errno);
            exit(SOCKERROR);
        }
    }
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(sockfd_, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            log(Fatal, "Bind fail,%s:%d", strerror(errno), errno);
            exit(BINDERROR);
        }
    }

    void Listen()
    {
        int ret = listen(sockfd_, backlog);
        if (ret == -1)
        {
            log(Fatal, "Listen fail,%s:%d", strerror(errno), errno);
            exit(LISTENERROR);
        }
    }
    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(sockfd_, (struct sockaddr *)&peer, &len);
        if (newfd < 0)
        {
            log(Fatal, "Accept fail,%s:%d", strerror(errno), errno);
            return -1;
        }
        char ipstr[64];
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));
        *clientip = ipstr;
        // *clientip = inet_ntoa(peer.sin_addr);
        *clientport = ntohs(peer.sin_port);
        return newfd;
    }
    bool Connect(const std::string clientip, const uint16_t clientport)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(clientport);
        inet_pton(AF_INET, clientip.c_str(), &(peer.sin_addr));
        // inet_aton(clientip.c_str(),&peer.sin_addr);
        int n = connect(sockfd_, (struct sockaddr *)&peer, sizeof(peer));
        if (n == -1)
        {
            std::cerr << "Connect fail, " << strerror(errno) << " errno: " << errno << std::endl;
            return false;
        }
        return 1;
    }
    int Fd(){ return sockfd_; }
    void Close() { close(sockfd_); }

private:
    int sockfd_;
};
